#include <stdio.h>
#include <io.h>
#include <fcntl.h>

// simple things
#define null NULL
#define PI	3.14159265 


// All the better to debug you with, my dear.
void createConsole () {
	AllocConsole();
	HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);	
	int hCrt = _open_osfhandle((long)handle,_O_TEXT);
	FILE * hf = _fdopen( hCrt, "w" );
	char buf[2];
	setvbuf( hf, buf, _IONBF, 1 );
	*stdout = *hf;
}
//


void toLowerCase (char* string) {
	for	(char* letter = string; *letter != '\0'; letter++)
		if (*letter >= 65 && *letter <= 90)
			*letter += 32;
}
//

void toUpperCase (char* string) {
	for	(char* letter = string; *letter != '\0'; letter++)
		if (*letter >= 97 && *letter <= 122)
			*letter -= 32;
}
//

bool charInCString (char _char, char* _string) {
	for (int i = 0; i < strlen(_string); i++)
		if (_char == _string[i])
			return true;

	return false;
}
//

string next_word (string& str, string delimiters = string(" ,;:\t\n")) {

	int start = 0;
	while (start < str.length() && delimiters.find(str[start]) != -1)
		start++;

	int end = start;
	while (end < str.length() && delimiters.find(str[end]) == -1)
		end++;

	string word = str.substr(start, end-start);
	str = str.substr( min(end+1, str.length()-1) );

	return word;
}
//

void next_word (ifstream& input, char* word, short maxChars, char* delimiters = " ,;:\t\n") {
	input.get(word[0]);

	// advance until a non-delimeter character is found
	while (charInCString(word[0], delimiters))
		input.get(word[0]);

	// continue, copying chars into word[] UNTIL delimiter or EOF or out of space
	short pos = 0;
	while (!charInCString(word[pos], delimiters) && pos < maxChars && !input.eof()) {
		pos++;
		input.get(word[pos]);
	}

	word[pos] = '\0';
}
//

void back_up_one_word (ifstream& input, char* delimiters = " ,;:\t\n") {
	char _char;

	input.unget();
	_char = input.peek();

	// back up until a word is found
	while (charInCString(_char, delimiters)) {
		input.unget();
		_char = input.peek();		
	}

	// back up to the beginning of the word
	while (!charInCString(_char, delimiters) && input.tellg() > 0) {
		input.unget();
		_char = input.peek();
	}
}
//

int currentMatrixStack () {
	int mode; glGetIntegerv (GL_MATRIX_MODE, &mode);

	if		(mode == GL_MODELVIEW)	mode = GL_MODELVIEW_MATRIX;
	else if (mode == GL_PROJECTION) mode = GL_PROJECTION_MATRIX;
	else							mode = GL_TEXTURE_MATRIX;
	
	return mode;
}
//